import subprocess
import time
from datetime import datetime, timedelta
import numpy as np

# 定义每1分钟执行一次
interval = 30  # 1分钟（单位：秒）

# 目标命令中的其他参数
destination_ip = "192.168.20.20"  # 目标IP地址
mode = 2  # 模式（1 = 文件，2 = 随机）
host_label = "A"  # 主机标签
listen_flag = "--active"  # 活动模式

# 定义频率和数据包数量的数组
# frequency_array = [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000]  # 频率数组（单位：Hz）
frequency_array = [100, 200, 500, 1000]  # 频率数组（单位：Hz）
num_packets_array = [127, 255, 511, 1023, 2047]  # 数据包数量数组

def execute_ping_program(frequency_hz, num_packets):
    """
    执行 ping_program 命令。
    :param frequency_hz: 发包频率（Hz）
    :param num_packets: 数据包数量
    """
    # 动态生成 sequence_file
    sequence_file = f"n{int(np.ceil(np.log2(num_packets)))}s12"
    
    command = f"sudo ./ping_program {destination_ip} {num_packets} {frequency_hz} {mode} {sequence_file} {host_label} {listen_flag}"
    try:
        # 执行命令
        result = subprocess.run(command, shell=True, capture_output=True, text=True)
        
        # 打印命令输出
        if result.returncode == 0:
            print(f"Command executed successfully (frequency_hz = {frequency_hz}, num_packets = {num_packets}):\n{result.stdout}")
        else:
            print(f"Error executing command (frequency_hz = {frequency_hz}, num_packets = {num_packets}):\n{result.stderr}")
    except Exception as e:
        print(f"An error occurred: {e}")

def calculate_start_times():
    """
    计算当前时间加 2 分钟所在的整点分钟，以及另一个主机提前 5 秒的时间。
    :return: 主机A和主机B的启动时间
    """
    current_time = datetime.now()
    start_time = current_time + timedelta(minutes=2)
    
    # 设置为整点分钟
    start_time = start_time.replace(second=0, microsecond=0)

    # 主机B的时间提前 5 秒
    start_time_b = start_time - timedelta(seconds=5)

    print(f"Current time: {current_time.strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"Host A start time: {start_time.strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"Host B start time: {start_time_b.strftime('%Y-%m-%d %H:%M:%S')}")

    return start_time, start_time_b

def wait_until_time(target_time):
    """
    等待直到指定的目标时间。
    :param target_time: 目标时间
    """
    current_time = datetime.now()
    if current_time > target_time:
        print("Error Timer! Target time has already passed.")
        return

    wait_time = (target_time - current_time).total_seconds()
    print(f"Waiting for {wait_time} seconds until {target_time.strftime('%Y-%m-%d %H:%M:%S')}...")
    time.sleep(wait_time)

def main():
    """
    主函数：等待到指定开始时间，然后根据频率和数据包数量的组合执行命令。
    """

    for frequency_hz in frequency_array:
        for num_packets in num_packets_array:
            host_a_time, host_b_time = calculate_start_times()
            print("Waiting for Host A...", host_a_time)
            wait_until_time(host_a_time)
            execute_ping_program(frequency_hz, num_packets)
            
            # 等待计算的时间（基于频率和数据包数量计算）
            # wait_seconds = num_packets / frequency_hz
            # print(f"Waiting for {wait_seconds} seconds (frequency = {frequency_hz}, num_packets = {num_packets})...")
            # time.sleep(wait_seconds)

            # 执行命令后，等待固定的间隔时间
            # print(f"Waiting for {interval} seconds before the next execution...")
            # time.sleep(interval)

if __name__ == "__main__":
    main()

